package com.icehelper.hades.base.log;

import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.Marker;
import org.apache.logging.log4j.core.config.Property;
import org.apache.logging.log4j.core.impl.Log4jLogEvent;
import org.apache.logging.log4j.message.Message;

import java.util.List;
/**
 * @author Leon Sun
 */
public class HadesLogEvent extends Log4jLogEvent{

  private StackTraceElement source;
  private boolean sourceSearched = false;

  public HadesLogEvent() {
  }

  public HadesLogEvent(String loggerName, Marker marker, String loggerFQCN, Level level,
      Message message, List<Property> properties, Throwable t) {
    super(loggerName, marker, loggerFQCN, level, message, properties, t);
  }

  @Override
  public StackTraceElement getSource() {
    if (sourceSearched) {
      return source;
    }
    if (this.getLoggerFqcn() == null || !this.isIncludeLocation()) {
      return null;
    }

    // copied from org.apache.logging.log4j.util.StackLocator.calcLocation()
    final StackTraceElement[] stackTrace = new Throwable().getStackTrace();
    StackTraceElement last = null;
    for (int i = stackTrace.length - 1; i > 0; i--) {
      final String className = stackTrace[i].getClassName();
      if (this.getLoggerFqcn().equals(className)) {
        source = last;
        break;
      }
      last = stackTrace[i];
    }
    sourceSearched = true;
    return source;
  }
}
